package cn.kgc.springmvc.day03.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 课工场
 * @date 2024/5/7
 * @description  springmvc环境下如何实现session和cookie的操作
 */
@Controller
@RequestMapping("sc")
public class SCKController {


    @RequestMapping("m1")
    @ResponseBody
    public String  method1(HttpServletRequest request,HttpServletResponse resp){

        // 用户第一次访问 会创建一个会话对象  通过请求对象中是否含有JSESSIONID  ->session
        HttpSession session = request.getSession();
        String id = session.getId();
        System.out.println("id = " + id);
        session.setAttribute("sessionValue","sValue1");

        Cookie cookie = new Cookie("ck1","ckValue");
        resp.addCookie(cookie);

        return "hello session";
    }

    @RequestMapping("m2")
    @ResponseBody
    public String  method2(HttpServletRequest request,HttpServletResponse resp){

        HttpSession session = request.getSession();
        String sessionValue = (String) session.getAttribute("sessionValue");
        return "hello session " +sessionValue;
    }

    @RequestMapping("m3")
    @ResponseBody
    public String  method3( HttpSession session){
        String sessionValue = (String) session.getAttribute("sessionValue");
        return "hello session " +sessionValue;
    }


    @RequestMapping("m4")
    @ResponseBody
    public String  method4(@SessionAttribute("sessionValue") String sessionValue ){

        System.out.println("sessionValue = " + sessionValue);
        return "hello session " +sessionValue;
    }


    @RequestMapping("m5")
    @ResponseBody
    public String  method5(HttpServletRequest request,HttpServletResponse response){
        // 获取请求对象中的cookie
        Cookie[] cookies = request.getCookies();
        String value = null;
        for (Cookie cookie : cookies) {
            if ("ck1".equals(cookie.getName())){
              value  = cookie.getValue();
              break;
            }
        }
        return "hello cookie cookieValue =  "+value;
    }


    @RequestMapping("m6")
    @ResponseBody
    public String  method6(@CookieValue("ck1") String ckValue){

        return "hello cookie  cookieValue = "+ckValue;
    }



}
